package online.chazi.bootplus.autoconfiguation.multiple.datasource.aspect;

import online.chazi.bootplus.autoconfiguation.multiple.datasource.annotation.UsingDataSource;
import online.chazi.bootplus.multiple.datasource.MultipleDataSource;
import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;

import java.lang.reflect.Method;

/**
 * 说明：方法上的会比类上的优先。
 * Created by 叉子同学 on 2020-05-19 13:39
 */
public class DataSourceInterceptor implements MethodInterceptor {

    @Override
    public Object invoke(MethodInvocation invocation) throws Throwable {
        String ds = determineDataSource(invocation);
        if (ds != null)
            try {
                MultipleDataSource.push(ds);
                return invocation.proceed();
            } finally {
                MultipleDataSource.poll();
            }
        return invocation.proceed();
    }

    private String determineDataSource(MethodInvocation invocation) {
        Method method = invocation.getMethod();
        if (method.isAnnotationPresent(UsingDataSource.class)) {
            UsingDataSource uds = method.getAnnotation(UsingDataSource.class);
            return uds.name();
        } else {
            //找class有没有定义
            Class<?> target = invocation.getThis().getClass();
            if (target.isAnnotationPresent(UsingDataSource.class)) {
                return target.getAnnotation(UsingDataSource.class).name();
            }
        }
        return null;
    }

}
